package com.ainiyar.springweb.service.impl;

import com.ainiyar.springweb.common.result.ResultResponse;
import com.ainiyar.springweb.mapper.RegionMapper;
import com.ainiyar.springweb.pojo.admin.dto.PageDto;
import com.ainiyar.springweb.pojo.admin.dto.RegionDto;
import com.ainiyar.springweb.pojo.admin.vo.RegionVo;
import com.ainiyar.springweb.pojo.admin.vo.SelectVo;
import com.ainiyar.springweb.pojo.entity.Menu;
import com.ainiyar.springweb.pojo.entity.Region;
import com.ainiyar.springweb.service.RegionService;
import com.ainiyar.springweb.util.ChineseUtil;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.If;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

import static com.ainiyar.springweb.pojo.entity.table.MenuTableDef.MENU;
import static com.ainiyar.springweb.pojo.entity.table.RegionTableDef.REGION;
import static java.awt.SystemColor.menu;

/**************************************
 * File Name : RegionServiceImpl
 * Created with : IntelliJ IDEA.
 * Author : 艾尼亚尔·毛拉吾提
 * QQ : 524155792  WeChat : ainiyar0124
 * Created Time : 2024/2/16  22:26
 * Desc :
 ***************************************/
@Service
public class RegionServiceImpl extends ServiceImpl<RegionMapper, Region> implements RegionService {
    @Resource
    private RegionMapper regionMapper;

    /**
     * 区域列表
     *
     * @param pageDto   分页参数
     * @param regionDto 查询条件
     */
    @Override
    public ResultResponse<Object> lists(PageDto pageDto, RegionDto regionDto) {
        if (regionDto.getPId() == null) {
            regionDto.setPId(0);
        }
        QueryWrapper queryWrapper = QueryWrapper.create()
                .select(REGION.DEFAULT_COLUMNS)
                .where(REGION.NAME.like(regionDto.getName(), If::hasText))
                .and(REGION.P_ID.eq(regionDto.getPId(), If::notNull))
                .orderBy(REGION.ID.asc());
        Page<RegionVo> regionPage = Page.of(pageDto.getPage(), pageDto.getPageSize());
        regionPage = regionMapper.paginateAs(regionPage, queryWrapper, RegionVo.class);
        List<RegionVo> list = new ArrayList<>();
        for (RegionVo record : regionPage.getRecords()) {
            RegionVo region = new RegionVo();
            BeanUtils.copyProperties(record, region);
            if (record.getPId() == 0) {
                region.setPName("省级区域");
            } else {
                Region regionName = getRegionById(record.getPId());
                region.setPName(regionName.getName());
            }
            String level_name = switch (record.getLevel()) {
                case 1 -> "省级";
                case 2 -> "地级";
                case 3 -> "县级";
                case 4 -> "乡级";
                case 5 -> "村级";
                default -> "组级";
            };
            level_name = level_name + "行政区";
            region.setLevelName(level_name);
            region.setChildrenCount(getChildrenCount(record.getId()));
            list.add(region);
        }
        return ResultResponse.pageList(list, regionPage.getPageNumber(), regionPage.getPageSize(), regionPage.getTotalRow(), regionPage.getTotalPage());
    }

    /**
     * 保存新增，修改数据
     *
     * @param region_data 参数
     * @return true:成功  false:失败
     */
    @Override
    public boolean saveAddEdit(Region region_data) {
        Region region = new Region();
        if (region_data.getId() != null && region_data.getId() != 0) {
            region.setId(region_data.getId());
        }
        region.setName(region_data.getName());
        region.setInitial(ChineseUtil.getFirstPinyin(region_data.getName()));
        region.setPId(region_data.getPId());
        if (region_data.getPId() == 0) {
            region.setLevel(1);
        } else {
            Region regionLevel = getRegionById(region_data.getPId());
            region.setLevel(regionLevel.getLevel() + 1);
        }
        region.setLatitude(region_data.getLatitude());
        region.setLongitude(region_data.getLongitude());
        return regionMapper.insertOrUpdateSelective(region) > 0;
    }

    /**
     * 为下拉框
     */
    @Override
    public List<SelectVo> getRegionForSelect() {
        QueryWrapper queryWrapper = QueryWrapper.create()
                .select(REGION.DEFAULT_COLUMNS)
                .orderBy(REGION.ID.desc());
        List<Region> list = regionMapper.selectListByQuery(queryWrapper);
        return buildTreeVo(list, 0);
    }

    /**
     * 删除区域
     *
     * @param id 区域id
     * @return true:成功  false:失败
     */
    @Override
    public boolean del(Integer id) {
        return regionMapper.deleteById(id) > 0;
    }

    /**
     * 检查当前区域是否存在子区域
     *
     * @param id 当前区域id
     * @return true:存在  false:不存在
     */
    @Override
    public boolean hasRegionChildren(Integer id) {
        QueryWrapper queryWrapper = QueryWrapper.create()
                .select(REGION.DEFAULT_COLUMNS)
                .where(REGION.P_ID.eq(id));
        List<Region> list = regionMapper.selectListByQuery(queryWrapper);
        return !list.isEmpty();
    }


    /**
     * 树形结构
     *
     * @param regions 区域数据
     * @param pid     上级id
     * @return List<SelectValue>
     */
    private List<SelectVo> buildTreeVo(List<Region> regions, Integer pid) {
        List<SelectVo> tree_list = new ArrayList<SelectVo>();
        Optional.ofNullable(regions).orElse(new ArrayList<Region>())
                .stream().filter(item -> item != null && Objects.equals(item.getPId(), pid))
                .forEach(item -> {
                    SelectVo treeVo = new SelectVo();
                    treeVo.setLabel(item.getName());
                    treeVo.setKey(Long.valueOf(item.getId()));
                    //递归生成我们的路由
                    List<SelectVo> children = buildTreeVo(regions, item.getId());
                    treeVo.setChildren(!children.isEmpty() ? children : null);
                    tree_list.add(treeVo);
                });
        return tree_list;
    }

    /**
     * 根据区域id获取区域信息
     *
     * @param p_id 上级区域id
     * @return 区域数据
     */
    private Region getRegionById(Integer p_id) {
        return regionMapper.selectOneById(p_id);
    }

    /**
     * 获取当前区域的所有子区域数量
     *
     * @param id 区域id
     * @return 数量
     */
    private Integer getChildrenCount(Integer id) {
        QueryWrapper queryWrapper = QueryWrapper.create()
                .select(REGION.DEFAULT_COLUMNS)
                .where(REGION.P_ID.eq(id));
        List<Region> list = regionMapper.selectListByQuery(queryWrapper);
        Integer count = list.size();
        if (!list.isEmpty()) {
            for (Region record : list) {
                count += getChildrenCount(record.getId());
            }
        }
        return count;
    }
}

